package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrResponseVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author GRS
 * @email 1245089481@qq.com
 * @since 2023-09-10 14:00:44
 */
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService
{
    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params)
    {
        IPage<AttrEntity> page = this.page(
            new Query<AttrEntity>().getPage(params),
            new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr)
    {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);

        // 保存基本数据
        this.save(attrEntity);

        // 保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null)
        {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType)
    {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();

        wrapper
            .eq(catelogId != 0, AttrEntity::getCatelogId, catelogId)
            .eq(AttrEntity::getAttrType, "base".equalsIgnoreCase(attrType) ?
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        String key = (String) params.get("key");
        wrapper.and(
            StringUtils.hasText(key),
            item -> item
                .eq(AttrEntity::getAttrId, key)
                .or()
                .like(AttrEntity::getAttrName, key)
        );

        IPage<AttrEntity> page = this.page(
            new Query<AttrEntity>().getPage(params),
            wrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVo> responseVos = records
            .stream()
            .map(item ->
            {
                AttrResponseVo vo = new AttrResponseVo();

                BeanUtils.copyProperties(item, vo);

                // 设置分类名和分组名
                if ("base".equalsIgnoreCase(attrType))
                {
                    LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, item.getAttrId());
                    AttrAttrgroupRelationEntity one = relationDao.selectOne(queryWrapper);
                    if (one != null && one.getAttrGroupId() != null)
                    {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(one.getAttrGroupId());
                        vo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }

                CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
                if (categoryEntity != null)
                {
                    vo.setCategoryName(categoryEntity.getName());
                }

                return vo;
            }).collect(Collectors.toList());

        pageUtils.setList(responseVos);

        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId)
    {
        AttrResponseVo responseVo = new AttrResponseVo();
        AttrEntity attrEntity = this.getById(attrId);

        BeanUtils.copyProperties(attrEntity, responseVo);

        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrId);

        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(wrapper);

        // 设置分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            if (relationEntity != null)
            {
                responseVo.setAttrGroupId(relationEntity.getAttrGroupId());

                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());

                if (attrGroupEntity != null)
                {
                    responseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        List<Long> catelogPath = categoryService.findCatelogPath(catelogId);
        responseVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null)
        {
            responseVo.setCategoryName(categoryEntity.getName());
        }

        return responseVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr)
    {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId());
        Long count = relationDao.selectCount(queryWrapper);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            // 修改分组关联
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();

            entity.setAttrGroupId(attr.getAttrGroupId());
            entity.setAttrId(attr.getAttrId());

            LambdaUpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId());

            if (count > 0)
            {

                relationDao.update(entity, updateWrapper);
            }
            else
            {
                relationDao.insert(entity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId)
    {
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId);
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(wrapper);

        List<Long> attrIdList = entities
            .stream()
            .map(AttrAttrgroupRelationEntity::getAttrId)
            .collect(Collectors.toList());

        return attrIdList == null || attrIdList.isEmpty() ? null : this.listByIds(attrIdList);
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> voList)
    {
        //LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
        //wrapper
        //    .eq(AttrAttrgroupRelationEntity::getAttrId, 1L)
        //    .eq(AttrAttrgroupRelationEntity::getAttrGroupId, 1L);
        List<AttrAttrgroupRelationEntity> entities = voList
            .stream()
            .map(item ->
            {
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                BeanUtils.copyProperties(item, entity);
                return entity;
            })
            .collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId)
    {
        // 当前分组只能关联自己所属分类里的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 当前分组只能关联别的分组没有引用的属性
        // 当前分类下的其他分组
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper
            .eq(AttrGroupEntity::getCatelogId, catelogId);
        List<AttrGroupEntity> group = attrGroupDao.selectList(wrapper);
        List<Long> attrGroupIdList = group
            .stream()
            .map(AttrGroupEntity::getAttrGroupId)
            .collect(Collectors.toList());

        // 这些分组关联的属性
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityLambdaQueryWrapper =
            new LambdaQueryWrapper<>();
        wrapper.in(AttrGroupEntity::getAttrGroupId, attrGroupIdList);
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = relationDao.selectList(attrAttrgroupRelationEntityLambdaQueryWrapper);
        List<Long> attrIdList = attrgroupRelationEntityList
            .stream()
            .map(AttrAttrgroupRelationEntity::getAttrId)
            .collect(Collectors.toList());

        // 从当前分类的所有属性中移除这些属性
        LambdaQueryWrapper<AttrEntity> attrEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        attrEntityLambdaQueryWrapper
            .eq(AttrEntity::getCatelogId, catelogId)
            .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
            .notIn(attrIdList != null && !attrIdList.isEmpty(), AttrEntity::getAttrId, attrIdList);

        String key = (String) params.get("key");
        if (StringUtils.hasText(key))
        {
            attrEntityLambdaQueryWrapper.and(w -> w
                .eq(AttrEntity::getAttrId, key)
                .or()
                .like(AttrEntity::getAttrName, key)
            );
        }

        IPage<AttrEntity> pageModel = this.page(
            new Query<AttrEntity>().getPage(params),
            attrEntityLambdaQueryWrapper
        );

        return new PageUtils(pageModel);
    }
}